package com.hilinos.cloud.gateway;

import com.hilinos.cloud.gateway.router.JsfjReactorServiceInstanceLoadBalancer;
import com.hilinos.cloud.gateway.router.JsfjRoundRobinLoadBalancer;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import reactor.core.publisher.Mono;

@LoadBalancerClient(name = "自定义负载均衡", configuration = JsfjReactorServiceInstanceLoadBalancer.class)
@EnableDiscoveryClient
@SpringBootApplication
public class GatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }


    @Bean(value = "remoteAddrKeyResolver")
    public KeyResolver remoteAddrKeyResolver() {
        return exchange -> {
            return Mono.just(exchange.getRequest().getURI().getPath());
        };
    }

    // @Bean
    // public RedisRouteDefinitionRepository redisRouteDefinitionRepository() {
    //     return new RedisRouteDefinitionRepository(reactiveRedisTemplate);
    // }

    @Bean
    public ReactorLoadBalancer<ServiceInstance> reactorServiceInstanceLoadBalancer(Environment environment, ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        // return new JsfjRoundRobinLoadBalancer(serviceInstanceListSupplierProvider, name);
       return new JsfjReactorServiceInstanceLoadBalancer(serviceInstanceListSupplierProvider, name);
    }

}
